package com.dimeng;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Set;

import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.webkit.URLUtil;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.AutoCompleteTextView;
import android.widget.Gallery;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.PopupWindow.OnDismissListener;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.dimeng.adapter.GalleryAdapter;
import com.dimeng.entity.HomePhotoURLs;
import com.dimeng.utils.AppCache;
import com.dimeng.utils.CommonUtil;
import com.dimeng.utils.Constant;
import com.dimeng.utils.LoadDataThread;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

/**
 * app 入口主界面
 * 
 * @author ccn
 * 
 */
public class TaojindiActivity extends SuperActivity {
	private static final long serialVersionUID = -5560328652489067023L;
	private AutoCompleteTextView prodKeywordText;
	private ImageButton searchButton;

	private LinearLayout browsCatLayout;
	private LinearLayout lastInfoLayout;
	private LinearLayout priceLayout;
	private LinearLayout hotBuyLayout;
	private LinearLayout mettleLayout;
	private LinearLayout testLayout;
	private Resources resources;

	private int searchType;
	private TextView searchTypeNameTV;// 搜索类别名字
	private boolean indicateFlag;
	private LinearLayout searchLayout;
	private LinearLayout selectSearchLayout;
	private ImageView indicateImageView;
	/** 弹出选择搜索类别的窗口 **/
	private PopupWindow searchTypePopupWindow;
	/** 弹出窗口popupWindow中的新品图像按钮 **/
	private ImageButton prodImageButton;
	/** 弹出窗口popupWindow中的求购图像按钮 **/
	private ImageButton buyImageButton;
	/** 弹出窗口popupWindow中的公司图像按钮 **/
	private ImageButton comImageButton;

	private final String homePhotoUrl = Constant.HOST_URL + "homePhotoUrls.do";// 获取主页的相关图片action
	private HomePhotoURLs homePhotoURLs;
	private Thread loadDataThread;
	private LinkedHashMap<String, String> focusAndSkipUrlMap;// 主页焦点图及其对应的跳转url
	private String skipUrl;
	private LinkedHashMap<String, String> newProdAndSkipUrlMap;;// 新品图及其对应的跳转url
	private LinkedHashMap<String, String> goldMemberAndSkipUrlMap;;// 诚信商家图及其对应的跳转url

	private Gallery focusGallery;// 焦点图
	private GalleryAdapter galleryAdapter;
	private RelativeLayout showProdCompanyLayout;// 新品、诚信商家专区布局
	private LinearLayout newProdLayout;// 新品专区
	private LinearLayout newProdLeftLayout;// 新品专区左边的布局
	private ImageView newProdRightImage;// 新品专区右边的一张图片
	private LinearLayout goldShopLayout;// 诚信商家的布局

	public static LinkedHashMap<String, Bitmap> focusURLBitmap;// 主页焦点图及其对应的Bitmap对像集合
	private static ArrayList<String> focusBitmapUrlList = new ArrayList<String>();//焦点图的url List
	public static LinkedHashMap<String, Bitmap> newProdURLBitmap;// 新品图及其对应的Bitmap对像集合
	public static LinkedHashMap<String, Bitmap> goldMemberURLBitmap;// 诚信商家图及其对应的Bitmap对像集合
	private Thread loadBitmapsThread;// 下载焦点图线程
	private LinearLayout focusBottomLayout;// 焦点图下标布局--需要根据焦点图个数在此处动态增加下标个数//#00868B,android:layout_marginRight="5dp"
	private Thread changeFocusBottomThread;
	private int childViewCount = 0;
	private int currentFocusIndex = 0;
	static long seleepTimeByUser = 0L;//由用户滑动了焦点图，则为增加线程自动改变焦点图的等待时间
	private Gson gson = new Gson();
	private Context context;
	private Handler handler = new Handler() {
		public void handleMessage(final android.os.Message msg) {
			switch (msg.what) {
			case 0:
				Toast.makeText(TaojindiActivity.this, "已经加载完所有的数据了",
						Toast.LENGTH_SHORT).show();
				break;
			case 1:
				String gsonStr = (String) msg.obj;
				homePhotoURLs = gson.fromJson(gsonStr,
						new TypeToken<HomePhotoURLs>() {
						}.getType());
				startLoadBitmapsThread();
				break;
			case 2:
				Toast.makeText(TaojindiActivity.this, Constant.NET_ERROR,
						Toast.LENGTH_SHORT).show();
				break;
			case 3:
				if (null != focusURLBitmap && focusURLBitmap.size() > 0) {
					Set<String> keySet = focusURLBitmap.keySet();
					Iterator<String> it = keySet.iterator();
					while (it.hasNext()) {
						focusBitmapUrlList.add(it.next());
						TextView tv = new TextView(context);
						tv.setLayoutParams(new LinearLayout.LayoutParams(
								LinearLayout.LayoutParams.WRAP_CONTENT,
								LinearLayout.LayoutParams.WRAP_CONTENT));
						tv.setText("。");
						tv.setPadding(1, 0, 0, 0);
						focusBottomLayout.addView(tv);
					}
					galleryAdapter.notifyDataSetChanged();
					
					childViewCount = focusBottomLayout.getChildCount();
					setFocusPhotoAndBottomTextView();
					periodChangeFocusIndexThread();
					setNewProdGoldMemerPhoto();
					
					focusGallery.setBackgroundDrawable(null);
				}
				break;
			case 4:
				setFocusPhotoAndBottomTextView();
				break;
			default:
				break;
			}
		};
	};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		resources = getResources();
		Intent intent = getIntent();
		if (intent.getBooleanExtra("exit", false))
			CommonUtil.exit(this);// 退出系统
		setContentView(R.layout.main);
		context = this;
		CommonUtil.checkNetWorkStatus(this, true);
		searchType = intent.getIntExtra("searchType", 1);
		searchTypeNameTV = (TextView) findViewById(R.id.searchTypeNameId);
		prodKeywordText = (AutoCompleteTextView) findViewById(R.id.keywordId);
		indicateImageView = (ImageView) findViewById(R.id.searchTypeIndicate);
		searchLayout = (LinearLayout) this.findViewById(R.id.searchLayoutId);

		selectSearchLayout = (LinearLayout) LayoutInflater.from(this).inflate(
				R.layout.select_search_type, null);
		searchTypePopupWindow = new PopupWindow(selectSearchLayout);
		prodImageButton = (ImageButton) selectSearchLayout.getChildAt(0);// 从弹出窗布局selectSearchLayout中获取第一个组件
		buyImageButton = (ImageButton) selectSearchLayout.getChildAt(1);// 从弹出窗布局selectSearchLayout中获取第二个组件
		comImageButton = (ImageButton) selectSearchLayout.getChildAt(2);// 从弹出窗布局selectSearchLayout中获取第三个组件
		searchButton = (ImageButton) findViewById(R.id.searchButton);
		CommonUtil.setButtonFocusChanged(prodImageButton);// 设置图像按钮被点击的效果
		CommonUtil.setButtonFocusChanged(buyImageButton);// 设置图像按钮被点击的效果
		CommonUtil.setButtonFocusChanged(comImageButton);
		CommonUtil.setButtonFocusChanged(searchButton);
		
		// 以下为焦点图及新品、诚信商家展示视图
		focusGallery = (Gallery) findViewById(R.id.focusGalleryId);
		galleryAdapter = new GalleryAdapter(this,focusBitmapUrlList,focusGallery);
		galleryAdapter.notifyDataSetChanged();
		
		focusBottomLayout = (LinearLayout) findViewById(R.id.focusBottomLayoutId);
		showProdCompanyLayout = (RelativeLayout) findViewById(R.id.showProdCompanyLayoutId);
		newProdLayout = (LinearLayout) findViewById(R.id.newProdLayoutId);
		newProdLeftLayout = (LinearLayout) findViewById(R.id.newProdLeftLayoutId);
		newProdRightImage = (ImageView) findViewById(R.id.newProdRightImageId);
		goldShopLayout = (LinearLayout) findViewById(R.id.goldShopLayoutId);

		startLoadDataThread(homePhotoUrl);// 开始下载主页的相关图片
		//--菜单布局开始
		browsCatLayout = (LinearLayout) findViewById(R.id.browsCatLayoutId);
		lastInfoLayout = (LinearLayout) findViewById(R.id.lastInfoLayoutId);
		priceLayout = (LinearLayout) findViewById(R.id.priceLayoutId);
		hotBuyLayout = (LinearLayout) findViewById(R.id.hotBuyLayoutId);
		mettleLayout = (LinearLayout) findViewById(R.id.mettleLayoutId);
		testLayout = (LinearLayout) findViewById(R.id.testLayoutId);
		
		//--菜单布局设置按下手势背景变换及跳转事件开始
		Intent catBrowseIntent = new Intent(this,CatBrowseActivity.class);
		setMenuLayoutTouchChangeEvent(browsCatLayout, catBrowseIntent);//设置按下手势背景变换及跳转事件开始
		
		Intent lastInfoIntent = new Intent(this,InfoActivity.class);
		setMenuLayoutTouchChangeEvent(lastInfoLayout, lastInfoIntent);
		
		Intent priceIntent = new Intent(this,PriceBuyActivity.class);
		String titleLabel = resources.getString(R.string.price);
		String url = Constant.HOST_URL+ resources.getString(R.string.priceAction);
		priceIntent.putExtra("title", titleLabel);
		priceIntent.putExtra("url", url);
		priceIntent.putExtra("type", AppCache.PRICE);
		setMenuLayoutTouchChangeEvent(priceLayout, priceIntent);
		
		Intent hotBuyIntent = new Intent(this,PriceBuyActivity.class);
		titleLabel = resources.getString(R.string.hotBuy);
		url = Constant.HOST_URL + resources.getString(R.string.lastBuyAction);
		hotBuyIntent.putExtra("title", titleLabel);
		hotBuyIntent.putExtra("url", url);
		hotBuyIntent.putExtra("type", AppCache.LAST_BUY);
		setMenuLayoutTouchChangeEvent(hotBuyLayout, hotBuyIntent);
		
		Intent mettleIntent = new Intent(this,MettleActivity.class);
		setMenuLayoutTouchChangeEvent(mettleLayout, mettleIntent);
		
		Intent testIntent = new Intent(this,GalleryMettlePhotoActivity.class);
		setMenuLayoutTouchChangeEvent(testLayout, testIntent);
		
		CommonUtil.statVisit(context);//发送访问统计请求
		CommonUtil.checkAppUpdate(context,false);
		
		//--菜单布局设置按下手势背景变换及跳转事件结束
		//--菜单布局结束
		setSearchTypeName();
		prodKeywordText.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Intent intent = new Intent(TaojindiActivity.this, SupplyBuySearchActivity.class);
				if(2 == searchType)
					intent = new Intent(TaojindiActivity.this, CompanySearchActivity.class);
				intent.putExtra("searchType", searchType);
				TaojindiActivity.this.startActivity(intent);
			}
		});

		searchButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Intent intent = new Intent(TaojindiActivity.this,
						SupplyBuySearchActivity.class);
				String keyword = prodKeywordText.getText().toString().trim();
				if (!"".equals(keyword)) {
					intent.putExtra("keyword", keyword);
					TaojindiActivity.this.startActivity(intent);
				} else {// 使用动画提醒用户
					Animation shake = AnimationUtils.loadAnimation(context,
							R.anim.animlayout);
					searchLayout.startAnimation(shake);
					// Toast.makeText(TaojindiActivity.this, "请您输入搜索关键词",
					// Toast.LENGTH_SHORT).show();
				}
			}
		});

		searchLayout.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				if (!indicateFlag) {
					indicateFlag = true;
					indicateImageView.setImageDrawable(resources
							.getDrawable(R.drawable.up));

					searchTypePopupWindow.setWidth(searchLayout.getWidth()
							- searchButton.getWidth() - 2);
					searchTypePopupWindow.setHeight(LayoutParams.WRAP_CONTENT);
					searchTypePopupWindow.setBackgroundDrawable(resources
							.getDrawable(R.drawable.catListBG));
					searchTypePopupWindow
							.showAsDropDown(searchTypeNameTV, 0, 0);
					searchTypePopupWindow.setOutsideTouchable(true);
					searchTypePopupWindow.setFocusable(true);
					searchTypePopupWindow.update();
				} else {
					indicateFlag = false;
					indicateImageView.setImageDrawable(resources
							.getDrawable(R.drawable.down));
					if (null != searchTypePopupWindow) {
						searchTypePopupWindow.setFocusable(false);
						searchTypePopupWindow.dismiss();
					}
				}
			}
		});

		searchTypePopupWindow.setOnDismissListener(new OnDismissListener() {
			public void onDismiss() {
				indicateFlag = false;
				indicateImageView.setImageDrawable(resources
						.getDrawable(R.drawable.down));
			}
		});

		prodImageButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				searchType = 1;
				setSearchTypeName();
				searchTypePopupWindow.setFocusable(false);
				searchTypePopupWindow.dismiss();
			}
		});
		buyImageButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				searchType = 3;
				setSearchTypeName();
				searchTypePopupWindow.setFocusable(false);
				searchTypePopupWindow.dismiss();
			}
		});
		comImageButton.setOnClickListener(new OnClickListener() {// 跳转到公司搜索activity视图
			public void onClick(View v) {
				searchType = 2;
				setSearchTypeName();
				searchTypePopupWindow.setFocusable(false);
				searchTypePopupWindow.dismiss();
			}
		});
		
		focusGallery.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {
				clickImage(skipUrl);
			}
		});
		
		focusGallery.setOnItemSelectedListener(new OnItemSelectedListener(){
			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,int position, long arg3) {
				if(null != focusAndSkipUrlMap){
					String focusUrl = focusBitmapUrlList.get(position);
					skipUrl = focusAndSkipUrlMap.get(focusUrl);
					currentFocusIndex = position;
					setFocusBottomTextView(currentFocusIndex);
					TaojindiActivity.seleepTimeByUser += 6000;
					if(TaojindiActivity.seleepTimeByUser > 18000){
						TaojindiActivity.seleepTimeByUser = 18000;
					}
				}
			}
			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
		}});
	}

	/**
	 * 设置菜单布局的点击事件 手按下时改变该布局的背景色为红色；
	 * 手松开时设置背景为无，并跳转到相应的处理Activity视图
	 * **/
	private void setMenuLayoutTouchChangeEvent(LinearLayout layout,final Intent intent) {
		layout.setOnTouchListener(new OnTouchListener() {
			public boolean onTouch(View v, MotionEvent event) {
				if (event.getAction() == MotionEvent.ACTION_DOWN) {
					v.setBackgroundDrawable(resources
							.getDrawable(R.drawable.red));
				} else if (event.getAction() == MotionEvent.ACTION_UP) {
					v.setBackgroundDrawable(null);
					TaojindiActivity.this.startActivity(intent);
				} else {
					v.setBackgroundDrawable(null);
				}
				return true;
			}
		});
	}

	private void setSearchTypeName() {
		String searchTypeName = AppCache.SEARCH_TYPE_NAME_MAP.get(searchType);
		if (null != searchTypeName)
			searchTypeNameTV.setText(searchTypeName);
		indicateFlag = false;
		indicateImageView.setImageDrawable(resources
				.getDrawable(R.drawable.down));
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			CommonUtil.exit(this);// 退出系统
			return false;
		}
		return false;
	}

	/** 启动线程下载数据 **/
	private void startLoadDataThread(String url) {
		if (null == loadDataThread || !loadDataThread.isAlive()) {
			loadDataThread = new LoadDataThread(homePhotoUrl,Constant.CHARSET_GBK,handler,false);
			loadDataThread.start();
		}
	}

	private void startLoadBitmapsThread() {
		if (null == loadBitmapsThread || !loadBitmapsThread.isAlive()) {
			loadBitmapsThread = new Thread() {
				@Override
				public void run() {
					if (null != homePhotoURLs) {
						focusAndSkipUrlMap = homePhotoURLs
								.getFocusImageUrlMap();
						newProdAndSkipUrlMap = homePhotoURLs
								.getNewProdImageUrlMap();
						goldMemberAndSkipUrlMap = homePhotoURLs
								.getGoldMemberImageUrlMap();

						focusAndSkipUrlMap = replaceMapKey(focusAndSkipUrlMap);
						newProdAndSkipUrlMap = replaceMapKey(newProdAndSkipUrlMap);
						goldMemberAndSkipUrlMap = replaceMapKey(goldMemberAndSkipUrlMap);

						focusURLBitmap = CommonUtil.loadBitmap(focusAndSkipUrlMap.keySet());
						newProdURLBitmap = CommonUtil.loadBitmap(newProdAndSkipUrlMap.keySet());
						goldMemberURLBitmap = CommonUtil.loadBitmap(goldMemberAndSkipUrlMap.keySet());

						Message msg = new Message();
						msg.what = 3;
						handler.sendMessage(msg);
					}
				}
			};
		}
		loadBitmapsThread.start();

	}

	private LinkedHashMap<String, String> replaceMapKey(
			LinkedHashMap<String, String> likedMap) {
		if (null != likedMap) {
			LinkedHashMap<String, String> newMap = new LinkedHashMap<String, String>();
			Iterator<String> it = likedMap.keySet().iterator();
			while (it.hasNext()) {
				String url = it.next();
				String newUrl = CommonUtil.getResPath(url);
				newMap.put(newUrl, likedMap.get(url));
			}
			return newMap;
		}
		return null;
	}

	/** 周期性改变焦点图下标的线程 **/
	private void periodChangeFocusIndexThread() {
		if (null == changeFocusBottomThread
				|| !changeFocusBottomThread.isAlive()) {
			changeFocusBottomThread = new Thread() {
				int i = 0;
				public void run() {
					while (++i < 4) {//为了节省手机电量，此线程只改变3次焦点图后便退出
						try {
							if (null == focusURLBitmap || 0 == focusURLBitmap.size()) {
								Thread.sleep(4000);
								continue;
							}
							Thread.sleep(TaojindiActivity.seleepTimeByUser);
							TaojindiActivity.seleepTimeByUser = 0L;
							++currentFocusIndex;
							if (focusURLBitmap.size() == currentFocusIndex)
								currentFocusIndex = 0;
							Thread.sleep(2000);
							Message msg = new Message();
							msg.what = 4;
							handler.sendMessage(msg);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
				}
			};
			changeFocusBottomThread.start();
		}
	}

	private void setNewProdGoldMemerPhoto() {
		int showPCLayoutHeight = showProdCompanyLayout.getHeight();
		if (null != newProdURLBitmap && newProdURLBitmap.size() > 0
				&& null != newProdAndSkipUrlMap) {// 新品专区
			newProdLayout.setBackgroundDrawable(null);
			Set<String> keySet = newProdURLBitmap.keySet();
			int height = showPCLayoutHeight / (newProdURLBitmap.size() - 1);
			LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
					LinearLayout.LayoutParams.FILL_PARENT, height);
			int i = 0;
			Iterator<String> it = keySet.iterator();
			while (it.hasNext()) {
				final String url = it.next();
				final String skipUrl = newProdAndSkipUrlMap.get(url);
				Bitmap bm = newProdURLBitmap.get(url);
				if (0 == i) {// 第一张照片置于新品专区的右边,其余的垂直放置在新品专区的右边
					newProdRightImage.setImageBitmap(bm);
					newProdRightImage.setOnClickListener(new OnClickListener() {
						public void onClick(View v) {
							clickImage(skipUrl);
						}
					});
				} else {
					ImageView child = new ImageView(context);
					if (i > 1)
						lp.setMargins(0, 1, 0, 0);
					child.setLayoutParams(lp);
					child.setScaleType(ScaleType.CENTER_INSIDE);
					child.setImageBitmap(bm);
					child.setOnClickListener(new OnClickListener() {
						public void onClick(View v) {
							clickImage(skipUrl);
						}
					});
					newProdLeftLayout.addView(child);
				}
				++i;
			}
		}
		if (null != goldMemberURLBitmap && goldMemberURLBitmap.size() > 0
				&& null != goldMemberAndSkipUrlMap) {// 诚信商家
			goldShopLayout.setBackgroundDrawable(null);
			Set<String> keySet = goldMemberURLBitmap.keySet();
			int height = showPCLayoutHeight / goldMemberURLBitmap.size();
			LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
					LinearLayout.LayoutParams.FILL_PARENT, height);
			Iterator<String> it = keySet.iterator();
			int i = 0;
			while (it.hasNext()) {
				final String url = it.next();
				final String skipUrl = goldMemberAndSkipUrlMap.get(url);
				Bitmap bm = goldMemberURLBitmap.get(url);
				ImageView child = new ImageView(context);
				if (i > 0)
					lp.setMargins(0, 5, 0, 0);
				child.setLayoutParams(lp);
				child.setScaleType(ScaleType.CENTER_INSIDE);
				child.setImageBitmap(bm);
				child.setOnClickListener(new OnClickListener() {
					public void onClick(View v) {
						clickImage(skipUrl);
					}
				});
				goldShopLayout.addView(child);
				++i;
			}
		}
	}
	private void setFocusPhotoAndBottomTextView() {
		if (focusBitmapUrlList.size() == 0 || null == focusAndSkipUrlMap)
			return;
		focusGallery.setSelection(currentFocusIndex);
		String focusUrl = focusBitmapUrlList.get(currentFocusIndex);
		skipUrl = focusAndSkipUrlMap.get(focusUrl);
		setFocusBottomTextView(currentFocusIndex);
	}
	
	private void setFocusBottomTextView(int currentFocusIndex){
		for (int i = 0; i < childViewCount; i++) {
			TextView currentFocusTV = (TextView) focusBottomLayout.getChildAt(i);
			if (currentFocusIndex == i) {
				currentFocusTV.setTextColor(Color.rgb(255, 255, 255));
			} else {
				currentFocusTV.setTextColor(Color.rgb(0, 0, 0));
			}
		}
	}

	private void clickImage(String skipUrl) {
		if(null != skipUrl && !"".equals(skipUrl) && URLUtil.isNetworkUrl(skipUrl)){
			Intent intent = new Intent(TaojindiActivity.this, WebViewActivity.class);
			intent.putExtra("url", skipUrl);
			TaojindiActivity.this.startActivity(intent);
		}
	}
}